﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Data;
using Entity;
using System.Transactions;
namespace Background.Controllers
{
    [HandleError]
    public class HomeController : Controller
    {
        Data.Sql.Res_ItemRepository sqlRes_ItemRepository = null;
        Data.Redis.Res_ItemRepository redisRes_ItemRepository = null;
        public HomeController()
        {
            sqlRes_ItemRepository = new Data.Sql.Res_ItemRepository();
            redisRes_ItemRepository = new Data.Redis.Res_ItemRepository();
        }

        public ActionResult Index()
        {
            ViewData["Message"] = "欢迎使用 ASP.NET MVC!";

            return View();
        }

        public ActionResult About()
        {
            return View();
        }

        public ActionResult Res_Item(int? id)
        {
            var model = sqlRes_ItemRepository.GetModel();

            if (id.HasValue)
                model = model.Where(i => i.ID == id.Value);
            else
                model = model.Take(10);
            return View(model.ToList());
        }

        public ActionResult Details(int? id)
        {
            var model = sqlRes_ItemRepository.GetModel().FirstOrDefault(i => i.ID == id.Value);
            return View(model);
        }

        [HttpPost]
        public ActionResult Details(FormCollection form)
        {
            this.ValidateRequest = false;
            Res_Item entity = new Res_Item { ID = Convert.ToInt32(form["ID"]) };
            TryUpdateModel(entity);
            Res_Item entity2 = sqlRes_ItemRepository.GetDetailModel().FirstOrDefault(i => i.ID == Convert.ToInt32(form["ID"]));
            using (TransactionScope trans = new TransactionScope())
            {
                try
                {
                    #region 对SQL数据及redis缓存数据进行更新
                    //更新redis缓存数据库
                    redisRes_ItemRepository.Delete(entity2);
                    entity2.Name = entity.Name;
                    redisRes_ItemRepository.Insert(entity2);
                    //更新数据库
                    sqlRes_ItemRepository.Update(entity);
                    #endregion
                    trans.Complete();
                }
                catch (Exception)
                {

                    throw;
                }
                finally
                {
                    trans.Dispose();
                }
            }
            return RedirectToAction("Res_Item");
        }

    }
}
